package com.example.activities;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import com.example.common.CheckConnection;
import com.example.demo.R;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.GraphView.GraphViewData;
import com.jjoe64.graphview.GraphViewSeries;
import com.jjoe64.graphview.GraphViewStyle.GridStyle;
import com.jjoe64.graphview.LineGraphView;
import android.support.v7.app.ActionBarActivity;
import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class AsyncTaskDataByGraph extends ActionBarActivity {
	private GraphView graphView;
	private GraphViewSeries graphViewSeries;
	private GraphViewSeries graphViewSeries1;
	private GraphViewSeries graphViewSeries2;
	private final Handler mHandler = new Handler();
	private Runnable mTimer1;
	private double count = 1;
	private Button btnStart;
	private TextView txtState;
	private ListView lvData;
	private ProgressBar proState;
//	private Spinner spinUser, spinDevice;
	private boolean isGraphRunning = false;
	private boolean checkFirstRun = false;
	private static String USER = "user1";
	private static String DEVICE = "device1";
	private ArrayAdapter<String> arrData;
	private List<String> listdata, listTime;
	private List<Integer> listV1, listV2, listV3, listDevice, listUser;

	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_async_task_data_by_graph);
		btnStart = (Button) findViewById(R.id.btnStartGraph);
		txtState = (TextView) findViewById(R.id.txtDataServerName);
		lvData = (ListView) findViewById(R.id.listData);
		// spinUser = (Spinner) findViewById(R.id.spinUser);
		// spinDevice = (Spinner) findViewById(R.id.spinDevice);
		(proState = (ProgressBar) findViewById(R.id.proState))
				.setVisibility(View.GONE);
		listDevice = new ArrayList<Integer>();
		listUser = new ArrayList<Integer>();
		listTime = new ArrayList<String>();
		listdata = new ArrayList<String>();
		listV1 = new ArrayList<Integer>();
		listV2 = new ArrayList<Integer>();
		listV3 = new ArrayList<Integer>();
		arrData = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,
				listdata);
		lvData.setAdapter(arrData);
		CheckConnection conCheck = new CheckConnection(this);
		if (conCheck.isConnected()) {
			txtState.setText("You are connected to Interner!" + "\n "
					+ getResources().getString(R.string.data_from_ftico_server));
			txtState.setTextColor(Color.BLUE);
			btnStart.setOnClickListener(new OnClickListener() {
				@SuppressLint("ShowToast")
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					// USER = spinUser.getSelectedItem().toString();
					// DEVICE = spinDevice.getSelectedItem().toString();
					new asyncLoadUserAndDevice()
							.execute("http://10.3.9.147:1337/dataserie/findbyuseranddevice/"
									+ USER + "/" + DEVICE);

					btnStart.setClickable(false);
					btnStart.setAlpha((float) 0.4);
				}
			});
		} else {
			txtState.setText("You are not connected to Interner!");
			txtState.setTextColor(Color.RED);
			btnStart.setClickable(false);
			btnStart.setAlpha((float) 0.4);
		}

	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		isGraphRunning = false;
		checkFirstRun = true;
		mHandler.removeCallbacks(mTimer1);
		super.onPause();
	}

	private void initGraph(int a, int b, int c) {
		graphViewSeries = new GraphViewSeries("v1", null,
				new GraphViewData[] { new GraphViewData(1, a) });
		graphViewSeries1 = new GraphViewSeries("v2", null,
				new GraphViewData[] { new GraphViewData(1, b) });
		graphViewSeries2 = new GraphViewSeries("v3", null,
				new GraphViewData[] { new GraphViewData(1, c), });
		graphViewSeries.getStyle().color = Color.RED;
		graphViewSeries1.getStyle().color = Color.BLUE;
		graphViewSeries2.getStyle().color = Color.GREEN;

		graphView = new LineGraphView(AsyncTaskDataByGraph.this, "Line Graph");
		graphView.addSeries(graphViewSeries);
		graphView.addSeries(graphViewSeries1);
		graphView.addSeries(graphViewSeries2);

		graphView.getGraphViewStyle().setGridColor(Color.GREEN);
		graphView.getGraphViewStyle().setHorizontalLabelsColor(Color.YELLOW);
		graphView.getGraphViewStyle().setVerticalLabelsColor(Color.RED);
		graphView.getGraphViewStyle().setTextSize(
				getResources().getDimension(R.dimen.big));
		graphView.getGraphViewStyle().setNumHorizontalLabels(8);
		graphView.getGraphViewStyle().setVerticalLabelsWidth(40);
		graphView.setScalable(true);
		((LinearLayout) findViewById(R.id.lnlGraph)).addView(graphView);
	}

	private void runGraph(boolean checkGraphRunning) {
		if (isGraphRunning == false) {
			mHandler.postDelayed(mTimer1, 1000);
			isGraphRunning = true;
		}
	}

	public static String GET(String url) {
		InputStream inputStream = null;
		String result = "";
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
			inputStream = httpResponse.getEntity().getContent();
			if (inputStream != null) {
				result = convertInputStreamToString(inputStream);
			}
		} catch (Exception e) {
			Log.d("InputStream", e.getLocalizedMessage());
		}
		return result;
	}

	public static String convertInputStreamToString(InputStream inputStream)
			throws UnsupportedEncodingException {
		BufferedReader bufferedReader = new BufferedReader(
				new InputStreamReader(inputStream));
		String line = "";
		String result = "";
		try {
			while ((line = bufferedReader.readLine()) != null) {
				result += line;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.d("conver", "problem");
			e.printStackTrace();
		}
		try {
			bufferedReader.close();
			inputStream.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	// http://www.androidhive.info/2012/03/android-facebook-connect-tutorial/
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		mTimer1 = new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				count += 1;
				txtState.setText("Loading Graph.Please wait..."
				// + "\n Fletching: " + arrData.getItem((int) count)
				);
				if ((count % 2) == 0) {
					txtState.setTextColor(Color.BLUE);
				} else {
					txtState.setTextColor(Color.RED);
				}

				arrData.add(listUser.get((int) count) + "                 "
						+ listDevice.get((int) count) + "                 "
						+ "                   " + listV1.get((int) count) + ","
						+ listV2.get((int) count) + ","
						+ listV3.get((int) count) + "                 "
						+ "                 " + listTime.get((int) count));
				arrData.notifyDataSetChanged();
				lvData.setSelection(arrData.getCount() - 1);

				graphViewSeries.appendData(
						new GraphViewData(count, listV1.get((int) count - 1)),
						true, listV1.size());
				graphViewSeries1.appendData(
						new GraphViewData(count, listV2.get((int) count - 1)),
						true, listV1.size());
				graphViewSeries2.appendData(
						new GraphViewData(count, listV3.get((int) count - 1)),
						true, listV1.size());
				graphView.setViewPort(1, count);
				mHandler.postDelayed(this, 300);

				if (count == (listV1.size() - 1)) {
					checkFirstRun = false;
					txtState.setText("DONE!");
					mHandler.removeCallbacks(mTimer1);
				}
			}
		};
		if (isGraphRunning == false && checkFirstRun == true) {
			try {
				runGraph(isGraphRunning);
			} catch (Exception e) {
			}
		}
	}

	private class asyncLoadUserAndDevice extends
			AsyncTask<String, Integer, String> {
		private StringBuilder builder;

		asyncLoadUserAndDevice() {
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			proState.setVisibility(View.VISIBLE);
			txtState.setText("Loading Data!Please wait...");
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			// TODO Auto-generated method stub
		}

		@SuppressLint("NewApi")
		@Override
		protected String doInBackground(String... URL) {
			// TODO Auto-generated method stub
			builder = new StringBuilder();
			String line = "";
			HttpClient client = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(URL[0]);
			try {
				HttpResponse response = client.execute(httpGet);
				StatusLine statusLine = response.getStatusLine();
				int statusCode = statusLine.getStatusCode();
				if (statusCode == 200) {
					HttpEntity entity = response.getEntity();
					InputStream content = entity.getContent();
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(content));
					while ((line = reader.readLine()) != null) {
						builder.append(line.toString()).append("\n");
					}
				} else {
					Log.e("Getter", "Failed to download file");
				}
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

			return new String(builder.toString());
		}

		@SuppressWarnings("deprecation")
		@SuppressLint({ "NewApi", "ShowToast" })
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			proState.setVisibility(View.GONE);
			boolean checkResult = true;
			JSONArray jaray = null;
			JSONObject jObject;
			btnStart.setAlpha(0);
			btnStart.setClickable(false);
			Calendar cal = Calendar.getInstance();
			try {
				jObject = new JSONObject(result);
				jaray = jObject.getJSONArray("datarecord");
				int v1 = 0, v2 = 0, v3 = 0;
				for (int i = 0; i < jaray.length(); i++) {

					Long time = jaray.getJSONObject(i).getLong("timeOfDevice");
					cal.setTimeInMillis(time);
					listTime.add(cal.getTime().toGMTString());
					listUser.add(jObject.getJSONObject("dataserie").getInt(
							"_user"));
					listDevice.add(jObject.getJSONObject("dataserie").getInt(
							"_device"));
					v1 = (Integer) jaray.getJSONObject(i).get("v1");
					listV1.add(v1);
					v2 = (Integer) jaray.getJSONObject(i).get("v2");
					listV2.add(v2);
					v3 = (Integer) jaray.getJSONObject(i).get("v3");
					listV3.add(v3);

					// arrData.notifyDataSetChanged();
					// lvData.setSelection(listV1.size() -1);
				}

			} catch (Exception e) {
				checkResult = false;
				txtState.setText("problem, try again!" + "\n" + e.getMessage());
			}
			if (checkResult == true) {
				initGraph(listV1.get(0), listV2.get(0), listV3.get(0));
				graphView.setViewPort(1, 1);
				graphView.getGraphViewStyle()
						.setGridStyle(GridStyle.HORIZONTAL);
				graphView.setHorizontalGravity(0);
				graphView.setScrollable(true);
				runGraph(isGraphRunning);
				Toast.makeText(getApplicationContext(), "DONE! ", 1000).show();
				txtState.setText("Loading Graph! Please waiit");
			} else {
			}
		}
	}
}
